import { getAllCity } from '@/sub_pages/movie/common/api/movie.js';

// 设置当前选中城市
export function setCurrentCity(city) {
    uni.setStorageSync('select_city', city);
    getApp().globalData.subcontracting_movie.selectCity = city;
}

// 获取当前选中城市
export function getCurrentCity() {
    let city = getApp().globalData.subcontracting_movie.selectCity;
    if (Object.keys(city).length == 0) {
        city = uni.getStorageSync('select_city');
    }
    return city || {};
}

// 把字符串转成json格式，并检查请求是否成功
export function jsonParseCheck(str) {
    if (typeof str !== 'string') return false;

    const res = JSON.parse(str);
    if (res.code !== 0) {
        uni.$u.toast(res.msg);
        return false;
    } else {
        return res.data;
    }
}

// 获取所有城市数据
export async function getAllCitys() {
    return new Promise(resolve => {
        getAllCity().then(({ data }) => {
            const res = data.data;

            if (res) {
                uni.setStorageSync('citys_all', res);
                let para = getCurrentCity();
                // 初始化默认选择第一个城市
                if (!getCurrentCity() || Object.keys(para).length == 0) {
                    setCurrentCity(res[0]);
                }
                resolve(res);
            }
        });
    });
}
